package org.goyo.main.web.controller.system;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.excel.ExcelUtil;
import org.goyo.common.utils.JSONUtil;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.entity.system.SysDepGroup;
import org.goyo.main.domain.entity.system.SysMenu;
import org.goyo.main.domain.entity.system.SysRole;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.domain.entity.system.SysUserDepGroup;
import org.goyo.main.domain.entity.system.SysUserMenu;
import org.goyo.main.domain.entity.system.SysUserRole;
import org.goyo.main.domain.excelBean.CustomerExcel;
import org.goyo.main.domain.excelBean.SysUserExcel;
import org.goyo.main.services.log.MethodLog;
import org.goyo.main.services.system.ISysDepGroupService;
import org.goyo.main.services.system.ISysMenuService;
import org.goyo.main.services.system.ISysRoleService;
import org.goyo.main.services.system.ISysUserDepGroupService;
import org.goyo.main.services.system.ISysUserMenuService;
import org.goyo.main.services.system.ISysUserRoleService;
import org.goyo.main.services.system.ISysUserService;
import org.goyo.main.services.system.ISystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
 * 系统用户
 * 
 * @author chenchuan
 * 2014年10月23日
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController {
  private static Logger logger = LoggerFactory.getLogger(SysUserController.class);
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private ISysRoleService sysRoleService;
	@Resource
	private ISysUserRoleService sysUserRoleService;
	@Resource
	private ISysDepGroupService sysDepGroupService;
	@Resource
	private ISysUserDepGroupService sysUserDepGroupService;
	@Resource
	private ISysUserMenuService sysUserMenuService;
	@Resource
	private ISysMenuService sysMenuService;
	@Resource
	private ISystemService systemService;

	/**
	 * 用户删除
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/delSysUser")
	@ResponseBody
	public AjaxResult delSysUser(HttpServletRequest request,HttpServletResponse response){
		AjaxResult result = null;
		try {
			String rows = request.getParameter("rows");
			JSONArray jsonarray = JSONArray.fromObject(rows);
			List<SysUser> list = (List<SysUser>)JSONArray.toCollection(jsonarray, SysUser.class);
			String remsg = "";
			for (int i = 0; i < list.size(); i++) {
			  SysUser sysUser = list.get(i);
			  if(sysUser.isSupper()){
                remsg +=sysUser.getUsername()+"无法删除. ";
                list.remove(i);
                i--;
              }
            }
			if(null!=list && list.size()>0){
			  sysUserService.delByUuids(ToolUtils.getFiles(list,"uuid").toArray());
			}
			if(StringUtils.isEmpty(remsg)){
			  result = AjaxResult.resultSuccess("删除成功", null);
			}else{
			  result = AjaxResult.resultSuccess(remsg, null);
			}
		} catch (Exception e) {
			result = AjaxResult.resultFail("删除失败", null);
			logger.error(e.getMessage(),e);
		}
		
		return result;
	}
	
	/**
	 * 用户保存
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/saveOrUpdateSysUser")
	@ResponseBody
	public AjaxResult saveOrUpdateSysUser(HttpServletRequest request,HttpServletResponse response,Model model){
		AjaxResult result = null;
		String form = request.getParameter("form");
		SysUser sysUser = JSONUtil.json2Obj(form, SysUser.class);
		String rows = request.getParameter("rows");
		String groupIds = request.getParameter("treeData");
		String menuIds = request.getParameter("treeData2");

		JSONArray jsonarray = JSONArray.fromObject(rows);
		List<SysRole> list = (List<SysRole>)JSONArray.toCollection(jsonarray, SysRole.class);
		try {
			SysUser info = sysUserService.saveOrUpdateInfo(sysUser,list,groupIds,menuIds);
			systemService.refreshDepGroup();
			result = AjaxResult.resultSuccess("保存成功", info);
		} catch (Exception e) {
			result = AjaxResult.resultFail("保存失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 查看用户
	 * 
	 * @author chenchuan
	 * 2014年10月25日
	 */
	@RequestMapping("/viewSysUser")
	public String viewSysUser(HttpServletRequest request,Model model){
		String uuid = request.getParameter("uuid");
		SysUser info = null;
		try {
			info = sysUserService.findByUuid(uuid);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		model.addAttribute("info", JSONUtil.obj2Json(info));
		model.addAttribute("status", Constants.VIEW);
		return "/system/sysUserEdit";
	}
	
	/**
	 * 修改用户
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/alterSysUser")
	public String alterSysUser(HttpServletRequest request,Model model){
		String uuid = request.getParameter("uuid");
		SysUser info = null;
		try{
			if(uuid != null && !"".equals(uuid))
				info = sysUserService.findByUuid(uuid);
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
		model.addAttribute("info", JSONUtil.obj2Json(info));
		model.addAttribute("status", Constants.EDIT);
		return "/system/sysUserEdit";
	}
	
	/**
	 * 添加用户
	 * 
	 * @author chenchuan
	 * 2014年10月25日
	 */
	@RequestMapping("/addSysUser")
	public String addSysUser(Model model){
		model.addAttribute("status", Constants.NEW);
		return "/system/sysUserEdit";
	} 
	
	/**
	 * 用户list
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/toSysUserList")
	public String toUserList(HttpServletRequest request,Model model){
		return "/system/sysUserList";
	}
	
	@RequestMapping("/listData")
	@ResponseBody
	public String getListData(HttpServletRequest request,Model model){
		
		JSONObject data = null;
		//获取条件
		//Map<String, Object> cond = JSONUtil.json2Map(request.getParameter("cond"));
		//分页条件
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		String sortname = request.getParameter("sortname");
		String sortorder = request.getParameter("sortorder");
		
		String where = request.getParameter("where"); 
		//分页器
		Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
		try {
			pager = sysUserService.findByCondition(where, pager);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Rows", pager.getList());
			map.put("Total", pager.getCount());
			data = JSONObject.fromObject(map);
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		} 
		return data.toString();
	}
	
	/**
	 * 获取角色
	 * 
	 * @author chenchuan
	 * 2014年11月2日
	 */
	@RequestMapping("/listRoleData")
	@ResponseBody
	public String listRoleData(HttpServletRequest request,Model model){
		
		String userId = request.getParameter("userId");
		Map<String, Object> cond = new HashMap<String, Object>();
		JSONObject data = null;
		//分页条件
//		int page = Integer.parseInt(request.getParameter("page"));
//		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
//		String sortname = request.getParameter("sortname");
//		String sortorder = request.getParameter("sortorder");
		//分页器
//		Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
		Pager<SysRole> pager = null;
		try {
			pager = sysRoleService.findByCondition(null, new Pager<SysRole>());
			Map<String,Object> map = new HashMap<String,Object>();
			
			//查找用户角色表
			List<SysUserRole> userRoles = sysUserRoleService.findByUserId(userId);
			List<SysRole> roles = pager.getList();
			for(SysRole role : roles){
				for(SysUserRole userRole : userRoles){
					if(role.getUuid().equals(userRole.getRoleId())){
						role.setIschecked(true);
					}
				}
			}
			map.put("Rows",roles);
			map.put("Total", pager.getCount());
			data = JSONObject.fromObject(map);
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		} 
		return data.toString();
	}
	
	/**
	 * 获取组织树
	 * 
	 * @author chenchuan
	 * 2014年11月2日
	 */
	@RequestMapping("/listDepGroupData")
	@ResponseBody
	public List<SysDepGroup> listDepGroupData(HttpServletRequest request){
		List<SysDepGroup> list = null;
		String userId = request.getParameter("userId");
		try {
			list = sysDepGroupService.getAllSysDepGroup();
			if(userId != null){
				List<SysUserDepGroup> userGroups = sysUserDepGroupService.findByUserId(userId);
				for(SysDepGroup group : list){
					for(SysUserDepGroup userGroup : userGroups){
						if(group.getUuid().equals(userGroup.getDepGroupId()))
							group.setIschecked(true);
					}
				}
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return list;
	}
	
	/**
	 * 获取菜单树
	 * 
	 * @author chenchuan
	 * 2014年11月2日
	 */
	@RequestMapping("/listMenuData")
	@ResponseBody
	public List<SysMenu> listMenuData(HttpServletRequest request){
		List<SysMenu> list = null;
		String userId = request.getParameter("userId");
		try {
			list = sysMenuService.getAllSysMenu();
			if(userId != null){
				List<SysUserMenu> userMenus = sysUserMenuService.findByUserId(userId);
				for(SysMenu menu : list){
					for(SysUserMenu userMenu : userMenus){
						if(menu.getUuid().equals(userMenu.getMenuId()))
							menu.setIschecked(true);
					}
				}
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return list;
	}
	
	  @RequestMapping("/checkUserName")
	  public void checkUserName(HttpServletRequest request, HttpServletResponse response) throws IOException{
	    String uuid = request.getParameter("uuid");
	    String userName = request.getParameter("userName");
	    response.reset();
	    response.setContentType("text/html;charset=UTF-8");
	   //业务逻辑操作countByParams得到值并存储到num中
	    SysUser sysuser = null;
	    try {
	      if(StringUtils.isBlank(userName)){
	        response.getWriter().print(true);         
	      }else{
	        sysuser = sysUserService.findByUserName(userName);
	        if(null==sysuser){
	          response.getWriter().print(true);     
	        }else{
	          if(sysuser.getUuid().equals(uuid)){
	            response.getWriter().print(true);  
	          }else{
	            response.getWriter().print(false);
	          }
	        }
	      }
	    } catch (Exception e) {
	      response.getWriter().print(false);
	      logger.error(e.getMessage(),e);
	    }
	  }
	  @MethodLog("导入商品excle")
	  @RequestMapping("/importSysUserExcel")
	  @ResponseBody
	  public AjaxResult importSysUserExcel(HttpServletRequest request,HttpServletResponse response){
	    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	    MultipartFile files = multipartRequest.getFile("file");
	    if(files.getSize()!=0){
	        try {
	            Map<Object,Object> result = ExcelUtil.ExcelImportToObjec(SysUserExcel.class, ExcelUtil.getBytes(files.getInputStream()),false);
	            if(null!=result){
	                if(result.get(true)!=null){
	                    List<SysUserExcel> list = (List<SysUserExcel>) result.get(true);
	                    if(null!=list&&null!=list.get(0)){
	                    	sysUserService.saveOrUpdateSysUserList(list);
	                    }else{
	                        return  AjaxResult.resultFail("数据不完整，请检查后导入！",null);
	                    }
	                    int validData = list.size();
	                    return AjaxResult.resultSuccess("导入成功，共保存"+validData+"条数据！",null);
	                }else if(result.get(false)!=null){
	                    return AjaxResult.resultFail((String)result.get(false),null);
	                }else{
	                    return AjaxResult.resultFail("发生错误，导入失败！",null);
	                }
	            }else{
	                return AjaxResult.resultFail("可转换内容为空，导入失败！",null);
	            }
	        }catch (Exception e) {
	            logger.error(e.getMessage(), e);
	            return AjaxResult.resultFail("发生错误，导入失败！",null);
	        }
	    }else{
	        return AjaxResult.resultFail("文件大小为零，导入失败！",null);
	    }
	  }
}
